import re
from django.contrib.auth.backends import ModelBackend
from apps.ausers.models import User
from meiduo_mall.settings.dev import logger

#封装函数
def get_user_by_account(account):
    try:
        #新增 手机号校验
        if re.match(r"^1[345789]\d{9}$",account):
            user=User.objects.get(mobile=account)
        else:
            user=User.objects.get(username=account)
    except Exception as e:
        logger.error(e)
        return None
    else:
        return user
class UsernameMobileAuthBackend(ModelBackend):
    #重写函数
    def authenticate(self, request, username=None, password=None, **kwargs):
        #接收账户
        user=get_user_by_account(username)
        #校验密码是否正确
        if user and user.check_password(password):
            return user
